<template>
  <div>
    <el-cascader
      ref="cascaderHandle"
      v-model="departValue"
      style="width: 100%"
      :options="departList"
      :props="props"
      :show-all-levels="false"
      @change="closeCascader"
    ></el-cascader>
  </div>
</template>

<script>
import {departmentTree} from "@/ModulePermission/api/Permission/PermissionDepartment.js";
import { getTreeData } from "../utils/tool";
export default {
  name: "DepartList",
  components: {},
  props: {
    value: {
      type: Array,
      default: () => [], // 必填
    },
    level: {
      type: Number,
      default: -1,
    },
  },
  data() {
    return {
      props: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true,
      },
      departValue: [],
      departList: [],
      setLevel: 0,
    };
  },
  watch: {
    value(val) {
      Array.isArray(val) && (this.departValue = val);
    },
  },
  mounted() {
    this.initData();
  },
  methods: {
    getAllParentNode(treeData, id, parentKey) {
      const temp = [];
      // 递归函数
      const forFn = function(data, id, parentKey) {
        // 遍历树
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          if (item.id === id) {
            // 查找到指定节点加入集合
            temp.unshift(item.id);
            // 查找其父节点
            forFn(treeData, item[parentKey], parentKey);
            // 不必向下遍历，跳出循环
            break;
          } else {
            if (item.children) {
              // 向下查找到id
              forFn(item.children, id, parentKey);
            }
          }
        }
      };
      forFn(treeData, id, parentKey);
      return temp;
    },
    closeCascader() {
      this.$emit("input", this.departValue);
      this.$refs.cascaderHandle.dropDownVisible = false;
    },
    initData() {
      departmentTree({ status: 1 })
        .then((res) => {
          //  this.departList = this.setTreeData(res.data);
          // this.setTreeData(this.departList);
          if (this.level === -1) {
            this.departList = getTreeData(res.data);
          } else {
            this.departList = this.setTreeData(res.data);
          }
        });
    },
    setTreeData(data) {
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          data[i].children.forEach((element) => {
            if (element.children) {
              element.children = undefined;
            }
          });
        }
      }

      return data;
    },
  },
};
</script>
